/** 
 * Copyright (c) 2012 Beny Information Technology Co., Ltd. All Rights Reserved. 
 * <p>
 * Project Name:  奔逸协同工作平台
 * FileName：g.beny.framework.util.ImageCodeBulider.java 
 * Created On: 2012-7-28 下午8:31:07
 * Description: 
 * @author gson
 * @version 1.0
 * <p>
 * Modifier： 2012-7-28 下午8:31:07
 * Modify Time： 2012-7-28 下午8:31:07
 */
package g.beny.framework.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

import org.nutz.log.Log;
import org.nutz.log.Logs;

/**
 * 验证码生成
 * 
 * @ClassName: ImageCodeBulider
 * @Description: 验证码生成
 * @author gson
 * @date 2012-7-28 下午8:31:07
 * 
 */
public final class ImageCodeBulider {
	private static final Log log = Logs.getLog(ImageCodeBulider.class);

	private final static String baseCode = "qwertyuiopasdfghjklzxcvbnmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	private String code = "";
	private byte[] imgData = new byte[] {};

	private ImageCodeBulider() {}

	/**
	 * 生成
	 * 
	 * @methodName: gen
	 * @Description:
	 * @CreatedOn: 2012-8-3 下午2:34:07
	 * @author gson
	 * @return
	 */
	public final static ImageCodeBulider gen() {
		ImageCodeBulider b = new ImageCodeBulider();
		
		BufferedImage img = new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);
		// 得到该图片的绘图对象
		Graphics g = img.getGraphics();
		Random r = new Random();
		Color c = new Color(200, 150, 255);
		g.setColor(c);
		// 填充整个图片的颜色
		g.fillRect(0, 0, 68, 22);
		// 向图片中输出数字和字母
		StringBuffer sb = new StringBuffer();
		char[] ch = baseCode.toCharArray();
		int index, len = ch.length;
		for (int i = 0; i < 4; i++) {
			index = r.nextInt(len);
			g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
			g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));
			// 输出的 字体和大小
			g.drawString("" + ch[index], (i * 15) + 3, 18);
			// 写什么数字，在图片的什么位置画
			sb.append(ch[index]);
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			ImageIO.write(img, "jpeg", baos);
		} catch (IOException e) {
			if (log.isErrorEnabled()) {
				log.error(e.getMessage());
			}
			return b;
		}
		
		b.code = sb.toString().toLowerCase();
		b.imgData = baos.toByteArray();
		return b;
	}

	public String getCode() {
		return code;
	}

	public byte[] getImgData() {
		return imgData;
	}
}
